<?php

class MemberController extends Zend_Controller_Action
{
	/**
	 *
	 * Index action will be redirected to the home page
	 *
	 *
	 */
	function indexAction()
	{
		$this->_redirect('member/listtype');
	}

	/**
	 *
	 * List types action
	 *
	 *
	 */
	function listtypeAction()
	{
		$this->view->title = "Manage types of users";
		// get registry, access levels and translator
		$registry = Zend_Registry::getInstance();
		$access_levels = $registry->get('access_level_config');
		$translator = $registry->get('Zend_Translate');

		// initialize a UserTypes mode
		$types = new UserTypes();
		$this->view->types = $types->fetchAll();

		// list all types
		for($i = 0; $i < count($this->view->types); $i++){
			$level_name = 'level' . $this->view->types[$i]->access_level;
			if(isset($access_levels->$level_name->name)){
				$this->view->types[$i]->access_level = $translator->translate($access_levels->$level_name->name);
			}
		}
	}

	/**
	 *
	 * Add type action
	 *
	 */
	function addtypeAction()
	{
		$this->view->title = "Add new user type";

		// init from
		$form = new TypeForm();
		$this->view->form = $form;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			if($form->isValid($formData)){
				$types = new UserTypes();
				$row = $types->createRow();
				$row->type_name = $form->getValue('nameTypeForm');
				$row->access_level = $form->getValue('levelTypeForm');
				$row->save();
				$this->_redirect('member/listtype');
			} else {
				$form->populate($formData);
			}
		}
	}

	/**
	 *
	 * Delete type action
	 *
	 */
	function deletetypeAction(){
		$this->view->title = "Delete user type";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');
		if($this->_request->isPost()){
			$id = (int)$this->_request->getPost('id');
			$del = $this->_request->getPost('del');
			if($del == $translator->translate("Yes") && $id > 0){
				$types = new UserTypes();
				$where = 'id= ' . $id;
				$types->delete($where);
			}
			$this->_redirect('member/listtype');
		} else {
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$types = new UserTypes();
				$this->view->type = $types->fetchRow('id=' . $id);
				$level_name = 'level' . $this->view->type->access_level;
				if(isset($access_levels->$level_name->name)){
					$this->view->type->access_level = $translator->translate($access_levels->$level_name->name);
				}
			}
		}
	}

	/**
	 *
	 * Edit type action
	 *
	 */
	function edittypeAction()
	{
		$this->view->title = "Edit user type";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');

		$form = new TypeForm();
		$this->view->form = $form;

		if($this->_request->isPost()){ // processing post data
			$formData = $this->_request->getPost();
			if($form->isValid($formData)){
				$id = (int)$form->getValue('id');
				$types = new UserTypes();
				$row = $types->fetchRow('id=' . $id);
				$row->type_name = $form->getValue('nameTypeForm');
				$row->access_level = $form->getValue('levelTypeForm');
				$row->save();
				$this->_redirect('member/listtype');
			} else {
				$form->populate($formData);
			}
		}else{ // populate the form when user request edit action
				$id = (int)$this->_request->getParam('id', 0);
				if($id > 0){
					$types = new UserTypes();
					$type = $types->fetchRow('id=' . $id);
					//populate the form
					$form->getElement('id')->setValue($id);
					$form->getElement('nameTypeForm')->setValue($type->type_name);
					$form->getElement('levelTypeForm')->setValue($type->access_level);
					$form->getElement('submit')->setValue($translator->_('Edit'));
					//$form->populate($type->toArray());
				}
		}
	}


	/**
	 * Add agent action
	 */
	function addagentAction(){
		// page title
		$this->view->title = "Add agent";

		// attach password validator to passUserForm
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');

		// init from
		$form = new UserForm($access_levels->mobishop_level);
		$this->view->form = $form;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();

			// set up empty validator
			$empty_validator = new Zend_Validate_NotEmpty();
			$empty_validator->setMessage("This field is not left empty");
			$empty_validator->setTranslator($translator);

			// attach empty validator to pass and cpass
			$form->getElement('passUserForm')->addValidator($empty_validator);
			//$form->getElement('cpassUserForm')->addValidator($empty_validator);

			$pass_validator = new Zend_Validate_Identical($this->_request->getParam('passUserForm'));
			$pass_validator->setMessage("Confirm password and password aren't identical");
			$pass_validator->setTranslator($translator);
			$form->getElement('cpassUserForm')->addValidator($pass_validator);

			// attach username validator to the unameUserForm field
			$uname_validator = new Zend_Validate_NewUsername();
			$uname_validator->setTranslator($translator);
			$form->getElement('unameUserForm')->addValidator($uname_validator);

			// attach managedby validator
			$managedby_validator = new Zend_Validate_Managedby();
			$managedby_validator->setUserType($this->_request->getParam('typeUserForm'));
			$managedby_validator->setTranslator($translator);
			$form->getElement('supeUserForm')->addValidator($managedby_validator);
			// check whether the form is valid
			if($form->isValid($formData)){
				$users = new Users();
				$row = $users->createRow();
				$row->name = $form->getValue('nameUserForm');
				$row->email = $form->getValue('emailUserForm');
				$row->type_id = $form->getValue('typeUserForm');
				$row->city = $form->getValue('cityUserForm');
				$row->address = $form->getValue('addrUserForm');
				$row->telephone = $form->getValue('teleUserForm');
				$row->cellphone = $form->getValue('cellUserForm');
				$row->username = $form->getValue('unameUserForm');
				$row->password = md5($form->getValue('passUserForm'));
				$row->created_date = date('d/m/y H:i:s');
				$row->managed_by = $form->getValue('supeUserForm');
				$row->save();
				$this->_redirect('member/listagent');
			} else {
				$form->populate($formData);
				$form->getElement('submitUserForm')->setLabel('');
				$form->getElement('submitUserForm')->setValue($translator->_('Add'));
				$form->getElement('backUserForm')->setLabel('');
				$form->getElement('backUserForm')->setValue($translator->_('Back'));
			}
		}else{
			$form->getElement('submitUserForm')->setLabel('');
			$form->getElement('submitUserForm')->setValue($translator->_('Add'));
			$form->getElement('backUserForm')->setLabel('');
			$form->getElement('backUserForm')->setValue($translator->_('Back'));
		}

	}

	/**
	 * Delete agent action
	 */
	function deleteagentAction()
	{
		// page title
		$this->view->title = "Delete agent";
		// load translator
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');

		if($this->_request->isPost()){
			$id = (int)$this->_request->getPost('id');
			$del = $this->_request->getPost('del');
			if($del == $translator->translate("Yes") && $id > 0){
				$users = new Users();
				$where = 'id= ' . $id;
				$users->delete($where);
			}
			$this->_redirect('member/listagent');
		} else {
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$users = new Users();
				$select = $users->select()->from($users, array('username'))
       						->where('id=?', $id);
				$this->view->user = $users->fetchRow('id=' . $id);
			}
		}
	}


	/**
	 * Edit agent action
	 */
	function editagentAction()
	{
		// page title
		$this->view->title = "Edit agent";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');
		//get current member information
		$auth = Zend_Auth::getInstance();
		$member = $auth->getIdentity();

		// init from
		$form = new UserForm($access_levels->mobishop_level);

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			$users = new Users();
			$id = $this->_request->getParam('id');
			// check whehter this member is a salesman
			if($member->getAccessLevel == $access_levels->salesman_level){
				$row = $users->fetchRow('id= ' . $id . " AND managed_by = " . (int)$member->getId());
			}else{
				$row = $users->fetchRow('id= ' . $id );
			}
			if($row != NULL){
				$this->view->form = $form;

				// attach password validator to passUserForm if this field is not empty
				if($this->_request->getParam('passUserForm') != '')
				{
					$pass_validator = new Zend_Validate_Identical($this->_request->getParam('passUserForm'));
					$pass_validator->setMessage("Confirm password and password aren't identical");
					$pass_validator->setTranslator($translator);
					$form->getElement('cpassUserForm')->addValidator($pass_validator);
				}else{
					$form->getElement('passUserForm')->setRequired(false);
					$form->getElement('cpassUserForm')->setRequired(false);
				}
				// if the new username is not the same as the old username, validate it
				if($this->_request->getParam('unameUserForm') != $row->username){
					// attach username validator to the unameUserForm field
					$uname_validator = new Zend_Validate_NewUsername();
					$uname_validator->setTranslator($translator);
					$form->getElement('unameUserForm')->addValidator($uname_validator);
				}
				// attach managedby validator
				$managedby_validator = new Zend_Validate_Managedby();
				$managedby_validator->setUserType($this->_request->getParam('typeUserForm'));
				$managedby_validator->setTranslator($translator);
				$form->getElement('supeUserForm')->addValidator($managedby_validator);
				if($member->getAccessLevel() == $access_levels->salesman_level){
					$form->removeElement('supeUserForm');
				}

				// check whether the form is valid
				if($form->isValid($formData)){
					$row->name = $form->getValue('nameUserForm');
					$row->email = $form->getValue('emailUserForm');
					$row->type_id = $form->getValue('typeUserForm');
					$row->city = $form->getValue('cityUserForm');
					$row->address = $form->getValue('addrUserForm');
					$row->telephone = $form->getValue('teleUserForm');
					$row->cellphone = $form->getValue('cellUserForm');
					$row->username = $form->getValue('unameUserForm');
					if($form->getValue('passUserForm') != '')
					$row->password = md5($form->getValue('passUserForm'));
					if($member->getAccessLevel() == $access_levels->salesman_level){
						$row->managed_by = $member->getId();
					}else{
						$row->managed_by = $form->getValue('supeUserForm');
					}
					$row->save();
					$this->_redirect('member/listagent');
				} else {
					$form->populate($formData);
					$form->getElement('submitUserForm')->setLabel('');
					$form->getElement('submitUserForm')->setValue($translator->_('Edit'));
					$form->getElement('backUserForm')->setLabel('');
					$form->getElement('backUserForm')->setValue($translator->_('Back'));
				}
			}else{
				$this->view->message = $translator->_("This agent is currently not managed by you");
			}
		} else { // populate the form when user request edit action
			$id = (int)$this->_request->getParam('id', 0);
			if($id > 0){
					$users = new Users();
					// check whehter this member is a salesman
					if($member->getAccessLevel() == $access_levels->salesman_level){
						$user = $users->fetchRow('id= ' . $id . " AND managed_by = " . (int)$member->getId());
					}else{
						$user = $users->fetchRow('id= ' . $id );
					}
					if($user != NULL){
						$this->view->form = $form;
						if($member->getAccessLevel() == $access_levels->salesman_level){
							$form->removeElement('supeUserForm');
						}
						// populate the form
						$form->getElement('id')->setValue($id);
						$form->getElement('nameUserForm')->setValue($user->name);
						$form->getElement('emailUserForm')->setValue($user->email);
						$form->getElement('typeUserForm')->setValue($user->type_id);
						$form->getElement('cityUserForm')->setValue($user->city);
						$form->getElement('addrUserForm')->setValue($user->address);
						$form->getElement('teleUserForm')->setValue($user->telephone);
						$form->getElement('cellUserForm')->setValue($user->cellphone);
						$form->getElement('unameUserForm')->setValue($user->username);
						if($member->getAccessLevel() != $access_levels->salesman_level){
							$form->getElement('supeUserForm')->setValue($user->managed_by);
						}
						$form->getElement('submitUserForm')->setLabel('');
						$form->getElement('submitUserForm')->setValue($translator->_('Edit'));
						$form->getElement('backUserForm')->setLabel('');
						$form->getElement('backUserForm')->setValue($translator->_('Back'));
					}else{
						$this->view->message = $translator->_("This agent is currently not managed by you");
					}
			}

		}
	}

	/**
	 * List agent action
	 *
	 */
	function listagentAction(){

		// set page title
		$this->view->title = "List agent";
		$registry = Zend_Registry::getInstance();
		$access_levels = $registry->get('access_level_config');
		$paging_config = $registry->get('paging_config');

		//get current user information
		$auth = Zend_Auth::getInstance();
		$member = $auth->getIdentity();

		// init users database object
		$users = new Users();
		$userTypes = new UserTypes();
		// fetch rows to show
		$page = $this->_getParam('page',1);
		$select = $users->getAdapter()->select()
								->from(array('u' => 'vmg_user'))
					    	//	->limit(($page -1) * $paging_config->items, $page )
					            ->joinleft(array('t' => 'vmg_user_type'),
					                        'u.type_id = t.id', array('type_name', 'access_level'))
					            ->joinleft(array('v' => 'vmg_user'), 'u.managed_by = v.id', array('v.name as manager_name'))
					            ->where('t.access_level = ' . $access_levels->mobishop_level )
					            ->order('u.managed_by');
		if($member->getAccessLevel() == $access_levels->salesman_level ){
			$select = $select->where('u.managed_by = ?', (int)$member->getId());
		}
		$rows = $users->getAdapter()->fetchAll($select);

		// init paginator object
		$paginator = Zend_Paginator::factory($rows);
		$paginator->setItemCountPerPage($paging_config->items);
		$paginator->setCurrentPageNumber($page);
		// set paginator
		$this->view->paginator=$paginator;

		// init search form
		$searchForm = new UserSearchForm($access_levels->mobishop_level);
		$searchForm->setAction($this->getRequest()->getBaseUrl() . "/member/searchagent");
		$this->view->search_form = $searchForm;
	}

	/*
	 * Search agent action
	 */
	function searchagentAction(){
		// set page title
		$this->view->title = "Search agent";
		$registry = Zend_Registry::getInstance();
		$access_levels = $registry->get('access_level_config');
		$paging_config = $registry->get('paging_config');
		// get member info
		$auth = Zend_Auth::getInstance();
		$member = $auth->getIdentity();

		$searchForm = new UserSearchForm($access_levels->mobishop_level);
		if($this->_request->isPost()){ // get search conditions when user post information
			$formData = $this->_request->getPost();
			if($searchForm->isValid($formData)){
				$name = mysql_escape_string($searchForm->getValue('nameUserSearchForm'));
				$type = $searchForm->getValue('typeUserSearchForm');
				$page = 1;
			}
		}else{ // get search conditions when users naviagate through the pagination control
			$name = mysql_escape_string( $this->_request->getParam('nameUserSearchForm'));
			$type = $this->_request->getParam('typeUserSearchForm');
			// fetch rows to show
			$page = $this->_getParam('page',1);
		}
		$this->view->params = array('nameUserSearchForm'=> $this->view->escape($name), 'typeUserSearchForm'=>$type );
		// init users database object
		$users = new Users();
		$userTypes = new UserTypes();
		$select = $users->getAdapter()->select()
								->from(array('u' => 'vmg_user'))
					            ->joinleft(array('t' => 'vmg_user_type'),
					                        'u.type_id = t.id', array('type_name', 'access_level'))
					            ->joinleft(array('v' => 'vmg_user'), 'u.managed_by = v.id', array('v.name as manager_name'))
					            ->where('t.access_level = ?', $access_levels->mobishop_level )
							    ->where('u.name like ?', '%'. $name . '%' )
					            ;
		// check whether this member is a salesman
		if($member->getAccessLevel() == $access_levels->salesman_level){
			$select = $select->where('u.managed_by = ?', (int)$member->getId());
		}

		if($type > -1){
			$select = $select->where('u.type_id = ?', $type);
		}

		// init paginator object
		$paginator = Zend_Paginator::factory($select);
		$paginator->setItemCountPerPage($paging_config->items);
		$paginator->setCurrentPageNumber($page);

		// set paginator
		$this->view->paginator=$paginator;

		// init search form

		$searchForm->getElement('typeUserSearchForm')->setValue($type);
		$searchForm->getElement('nameUserSearchForm')->setValue($name);
		$searchForm->getElement('submitUserSearchForm')->setValue("Search");
		$this->view->search_form = $searchForm;

	}

	/*
	 * List salesman action
	 */
	function listsalesmanAction(){

		// set page title
		$this->view->title = "List salesman";
		$registry = Zend_Registry::getInstance();
		$access_levels = $registry->get('access_level_config');
		$paging_config = $registry->get('paging_config');
		// init users database object
		$users = new Users();
		$userTypes = new UserTypes();
		// fetch rows to show
		$page = $this->_getParam('page',1);
		$select = $users->getAdapter()->select()
								->from(array('u' => 'vmg_user'))
					    	//	->limit(($page -1) * $paging_config->items, $page )
					            ->joinleft(array('t' => 'vmg_user_type'),
					                        'u.type_id = t.id', array('type_name', 'access_level'))
					            ->joinleft(array('v' => 'vmg_user'), 'u.managed_by = v.id', array('v.name as manager_name'))
					            ->where('t.access_level < ' . $access_levels->mobishop_level . ' and access_level >' . $access_levels->admin_level);
		$rows = $users->getAdapter()->fetchAll($select);

		// init paginator object
		$paginator = Zend_Paginator::factory($rows);
		$paginator->setItemCountPerPage($paging_config->items);
		$paginator->setCurrentPageNumber($page);

		// set paginator
		$this->view->paginator=$paginator;

	}


	/**
	 * Add salesman action
	 */
	function addsalesmanAction(){
		// page title
		$this->view->title = "Add new salesman";

		// attach password validator to passUserForm
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');

		// init from
		$form = new UserForm($access_levels->salesman_level);
		$this->view->form = $form;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();

			// set up empty validator
			$empty_validator = new Zend_Validate_NotEmpty();
			$empty_validator->setMessage("This field is not left empty");
			$empty_validator->setTranslator($translator);

			// attach empty validator to pass and cpass
			$form->getElement('passUserForm')->addValidator($empty_validator);
			//$form->getElement('cpassUserForm')->addValidator($empty_validator);

			$pass_validator = new Zend_Validate_Identical($this->_request->getParam('passUserForm'));
			$pass_validator->setMessage("Confirm password and password aren't identical");
			$pass_validator->setTranslator($translator);
			$form->getElement('cpassUserForm')->addValidator($pass_validator);

			// attach username validator to the unameUserForm field
			$uname_validator = new Zend_Validate_NewUsername();
			$uname_validator->setTranslator($translator);
			$form->getElement('unameUserForm')->addValidator($uname_validator);

			// attach managedby validator
			$managedby_validator = new Zend_Validate_Managedby();
			$managedby_validator->setUserType($this->_request->getParam('typeUserForm'));
			$managedby_validator->setTranslator($translator);
			$form->getElement('supeUserForm')->addValidator($managedby_validator);
			// check whether the form is valid
			if($form->isValid($formData)){
				$users = new Users();
				$row = $users->createRow();
				$row->name = $form->getValue('nameUserForm');
				$row->email = $form->getValue('emailUserForm');
				$row->type_id = $form->getValue('typeUserForm');
				$row->city = $form->getValue('cityUserForm');
				$row->address = $form->getValue('addrUserForm');
				$row->telephone = $form->getValue('teleUserForm');
				$row->cellphone = $form->getValue('cellUserForm');
				$row->username = $form->getValue('unameUserForm');
				$row->password = md5($form->getValue('passUserForm'));
				$row->created_date = date('d/m/y H:i:s');
				$row->managed_by = $form->getValue('supeUserForm');
				$row->save();
				$this->_redirect('member/listsalesman');
			} else {
				$form->populate($formData);
				$form->getElement('submitUserForm')->setLabel('');
				$form->getElement('submitUserForm')->setValue($translator->_('Add'));
				$form->getElement('backUserForm')->setLabel('');
				$form->getElement('backUserForm')->setValue($translator->_('Back'));
			}
		}else{
			$form->getElement('submitUserForm')->setLabel('');
			$form->getElement('submitUserForm')->setValue($translator->_('Add'));
			$form->getElement('backUserForm')->setLabel('');
			$form->getElement('backUserForm')->setValue($translator->_('Back'));
		}

	}

	/**
	 * Edit salesman action
	 *
	 */
	function editsalesmanAction()
	{
		// page title
		$this->view->title = "Edit salesman";
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');
		$access_levels = $registry->get('access_level_config');
		// init from
		$form = new UserForm($access_levels->salesman_level);
		$this->view->form = $form;

		if($this->_request->isPost()){
			$formData = $this->_request->getPost();
			$users = new Users();
			$id = $this->_request->getParam('id');
			$row = $users->fetchRow('id=' . $id);

			// attach password validator to passUserForm if this field is not empty
			if($this->_request->getParam('passUserForm') != '')
			{
				$pass_validator = new Zend_Validate_Identical($this->_request->getParam('passUserForm'));
				$pass_validator->setMessage("Confirm password and password aren't identical");
				$pass_validator->setTranslator($translator);
				$form->getElement('cpassUserForm')->addValidator($pass_validator);
			}else{
				$form->getElement('passUserForm')->setRequired(false);
				$form->getElement('cpassUserForm')->setRequired(false);
			}
			// if the new username is not the same as the old username, validate it
			if($this->_request->getParam('unameUserForm') != $row->username){
				// attach username validator to the unameUserForm field
				$uname_validator = new Zend_Validate_NewUsername();
				$uname_validator->setTranslator($translator);
				$form->getElement('unameUserForm')->addValidator($uname_validator);
			}
			// attach managedby validator
			$managedby_validator = new Zend_Validate_Managedby();
			$managedby_validator->setUserType($this->_request->getParam('typeUserForm'));
			$managedby_validator->setTranslator($translator);
			$form->getElement('supeUserForm')->addValidator($managedby_validator);

			// check whether the form is valid
			if($form->isValid($formData)){
				$row->name = $form->getValue('nameUserForm');
				$row->email = $form->getValue('emailUserForm');
				$row->type_id = $form->getValue('typeUserForm');
				$row->city = $form->getValue('cityUserForm');
				$row->address = $form->getValue('addrUserForm');
				$row->telephone = $form->getValue('teleUserForm');
				$row->cellphone = $form->getValue('cellUserForm');
				$row->username = $form->getValue('unameUserForm');
				if($form->getValue('passUserForm') != '')
				$row->password = md5($form->getValue('passUserForm'));
				$row->managed_by = $form->getValue('supeUserForm');
				$row->save();
				$this->_redirect('member/listsalesman');
			} else {
				$form->populate($formData);
				$form->getElement('submitUserForm')->setLabel('');
				$form->getElement('submitUserForm')->setValue($translator->_('Edit'));
				$form->getElement('backUserForm')->setLabel('');
				$form->getElement('backUserForm')->setValue($translator->_('Back'));
			}
		} else { // populate the form when user request edit action
			$id = (int)$this->_request->getParam('id', 0);
			if($id > 0){
					$users = new Users();
					$user = $users->fetchRow('id=' . $id);
					//populate the form
					$form->getElement('id')->setValue($id);
					$form->getElement('nameUserForm')->setValue($user->name);
					$form->getElement('emailUserForm')->setValue($user->email);
					$form->getElement('typeUserForm')->setValue($user->type_id);
					$form->getElement('cityUserForm')->setValue($user->city);
					$form->getElement('addrUserForm')->setValue($user->address);
					$form->getElement('teleUserForm')->setValue($user->telephone);
					$form->getElement('cellUserForm')->setValue($user->cellphone);
					$form->getElement('unameUserForm')->setValue($user->username);
					$form->getElement('supeUserForm')->setValue($user->managed_by);
					$form->getElement('submitUserForm')->setLabel('');
					$form->getElement('submitUserForm')->setValue($translator->_('Edit'));
					$form->getElement('backUserForm')->setLabel('');
					$form->getElement('backUserForm')->setValue($translator->_('Back'));
			}

		}
	}

	/**
	 * Delete salesman action
	 */
	function deletesalesmanAction()
	{
		// page title
		$this->view->title = "Delete salesman";
		// load translator
		$registry = Zend_Registry::getInstance();
		$translator = $registry->get('Zend_Translate');

		if($this->_request->isPost()){
			$id = (int)$this->_request->getPost('id');
			$del = $this->_request->getPost('del');
			if($del == $translator->translate("Yes") && $id > 0){
				$users = new Users();
				$where = 'id= ' . $id;
				$users->delete($where);
			}
			$this->_redirect('member/listsalesman');
		} else {
			$id = (int)$this->_request->getParam('id');
			if($id > 0){
				$users = new Users();
				$select = $users->select()->from($users, array('username'))
       						->where('id=?', $id);
				$this->view->user = $users->fetchRow('id=' . $id);
			}
		}
	}

}

/**
 * This validator will be use to ensure that we won't have duplicated usernames in the database
 * @author nhchung
 *
 */
class Zend_Validate_NewUsername extends Zend_Validate_Abstract
{
	const MESSAGE = 'message';
	protected $_messageTemplates = array(
        self::MESSAGE => "The username '%value%' is not available"
    );

    public function isValid($value){
    	$this->_setValue($value);
    	$users = new Users();
    	$select = $users->select()->from($users, array('username'))
       			->where('username=?', $value);
		$rows = $users->fetchAll($select);
    	if(count($rows) > 0){
    		$this->_error();
    		return false;
    	}
    	return true;
    }
}

/**
 * This valiadate will be used to ensure that one lower access level member
 * will not be able to managed a higher access level member
 * @author nhchung
 *
 */
class Zend_Validate_Managedby extends Zend_Validate_Abstract
{
	const MESSAGE = 'message';
	const EXCEPTION = 'exception';
	var $_userType;
	protected $_messageTemplates = array(
        self::MESSAGE => "One user in a lower or equal access level can't managage a user in a higher access level"
    );

    public function setUserType($userType){
    	$this->_userType = $userType;
    }

    public function getUserLevel(){
    	$userTypes = new UserTypes();
    	$row = $userTypes->fetchRow('id = ' . $this->_userType);
    	return $row->access_level;
    }

    public function isValid($value){
    	$this->_setValue($value);
    	// get type_id of this supervisor
    	$users = new Users();
    	$userTypes = new UserTypes();
    	$select = $users->getAdapter()->select()
					    		->from(array('u' => 'vmg_user'), array(''))
					    		->where('u.id=' . $value)
					            ->joinleft(array('t' => 'vmg_user_type'),
					                        'u.type_id = t.id', array('access_level'));
	   	$row = $users->getAdapter()->fetchRow($select);
	    // compare the user type with this type_id
	    if((int)$this->getUserLevel() == 1){
	    	if((int)$this->getUserLevel() < (int)$row["access_level"]){
	    		$this->_error();
	    		return false;
	    	}
	    }else{
	    	if((int)$this->getUserLevel() <= (int)$row["access_level"]){
	    		$this->_error();
	    		return false;
	    	}
	    }
    	return true;
    }
}



